using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Collections;
using My.IdlConverter.Core;
using My.IdlConverter.Core.Producers;
using My.IdlConverter.Core.Filters;
using My.IdlConverter.Core.Util;

namespace My.IdlConverter.Com
{
    using Configuration = My.IdlConverter.Core.Cfg.Configuration;
    public class ComInterfaceProducer : InterfaceProducer
    {
        private string _baseInterfaceName = "IDispatch";

        public string BaseInterfaceName
        {
            get
            {
                return _baseInterfaceName;
            }
        }

        public ComInterfaceProducer()
        {
        }
        public ComInterfaceProducer(Interface consumer)
            : base(consumer)
        {
        }

        public ComInterfaceProducer(Interface consumer, string baseInterfaceName)
            : base(consumer)
        {
            _baseInterfaceName = baseInterfaceName;
        }

        public override string Produce()
        {
            StringBuilder sb = new StringBuilder();

            Guid iid = ComGuidCenter.Apply(Consumer.Name);
            string intfName = InterfaceModifier.GetName(Consumer.Name);

            string intfContent;
            IOHelper.ReadToEnd(System.IO.Path.Combine(Configuration.TemplatePath, @"idl_interface.txt"), out intfContent);
            intfContent = intfContent.Replace("%IID%", iid.ToString());
            intfContent = intfContent.Replace("%INTERFACE%", intfName);
            intfContent = intfContent.Replace("%PARENT_INTERFACE% ", BaseInterfaceName);

            sb.AppendLine(intfContent);
            sb.AppendLine("{");

            //sb.AppendLine("/*");

            IList<Method> methods = Consumer.Methods;
            ComPropertiesCollision propertiesCollision = MethodCollisionManager.Instance.GetCollision<ComPropertiesCollision>();
            if (methods.Count > 0)
            {
                ComMethodProducer methodProducer = new ComMethodProducer();
                for (int i = 0; i < methods.Count; ++i)
                {
                    Method nextMethod = methods[i];
                    int methodId = propertiesCollision.ResolveMethodId(nextMethod,i);

                    methodProducer.Consumer = nextMethod;
                    methodProducer.ID = methodId;
                    string methodString = methodProducer.Produce();
                    sb.AppendLine(StringUtil.FormatIndent1(methodString));

                    propertiesCollision.CacheMethods.Add(nextMethod);
                }
            }

            //sb.AppendLine("*/");

            sb.AppendLine("};");

            return sb.ToString();
        }
    }
}
